#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

pthread_mutex_t lock;

void routine(void*);
void* func(void*);

int main(int argc,char* argv[]){

  pthread_mutex_init(&lock,NULL);
  pthread_t tid;
  int ret;
  ret = pthread_create(&tid,NULL,func,NULL);
  if(ret){
    perror("pthread_create fail");
    exit(-1);
  }

  sleep(2);
  pthread_cancel(tid);

  pthread_mutex_lock(&lock);
  printf("hello world\n");
  pthread_mutex_unlock(&lock);

  pthread_join(tid,NULL);

  pthread_exit(NULL);
}

void* func(void* argv){
  pthread_cleanup_push(routine,NULL);
  int i = 0;
  while(i++ < 3){
    sleep(1);
    printf("world\n");
  }

  
  pthread_cleanup_pop(0);
  pthread_mutex_unlock(&lock);
  pthread_exit(NULL);
}


void routine(void* argv){
  pthread_mutex_unlock(&lock);
}
